package com.docker.core.mvc.controller;

import com.docker.core.constant.ConfigConstant;
import com.docker.core.third.docker.DockerKit;
import com.docker.core.third.docker.SelfDockerClient;
import com.docker.login.LoginRedis;
import com.docker.sys.app.AppBean;
import com.docker.sys.app.AppRedis;
import com.docker.sys.user.UserBean;
import com.jfinal.core.Controller;
import com.jfinal.kit.PropKit;
import com.jfinal.kit.StrKit;
import kit.docker.datetime.DateKit;
import kit.docker.exception.BaseException;
import kit.docker.validator.ValidatorKit;
import kit.docker.web.APIResCode;
import kit.docker.web.APIResponse;
import kit.docker.web.RequestKit;
import com.docker.core.third.websocket.WebsocketKit;
import org.apache.log4j.Logger;

import javax.websocket.Session;

public class BaseAPIController extends Controller {

    private static final Logger logger = Logger.getLogger(BaseAPIController.class);

    // =====================日志输出=======================================
    protected void logInfo(String msg) {
        logger.info(msg);
    }

    protected void logError(String msg) {
        logger.error(msg);
    }

    protected void logInfo(String msg, Throwable e) {
        logger.info(msg, e);
    }

    protected void logError(String msg, Throwable e) {
        logger.error(msg, e);
    }

    // =====================异常拦截处理=======================================

    protected void throwError(Integer status) {
        throw new BaseException(status);
    }

    protected void throwError(String message) {
        throw new BaseException(message);
    }

    protected void throwError(Integer status, String message) {
        throw new BaseException(status, message);
    }

    protected void throwError(Object data, Integer status, String message) {
        throw new BaseException(data, status, message);
    }

    // ===============接口响应数据结构封装==================
    protected void renderAPISuccess() {
        renderJson(APIResponse.success());
    }

    protected void renderAPISuccess(Object data) {
        renderJson(APIResponse.success(data));
    }

    protected void renderAPISuccess(Object data, String message) {
        renderJson(APIResponse.success(data, message));
    }

    protected void renderAPIFail() {
        renderJson(APIResponse.fail());
    }

    protected void renderAPIFailMessage(String message) {
        renderJson(APIResponse.failMessage(message));
    }

    protected void renderAPI(boolean res) {
        if (res) {
            renderAPISuccess();
        } else {
            renderAPIFail();
        }
    }

    // ===============通用参数获取=========================

    protected int getPageNum() {
        return getParaToInt(PropKit.get(ConfigConstant.SYS_PAGINATE_PAGENUM_NAME, "page_num"), 1);
    }

    protected int getPageSize() {
        return getParaToInt(PropKit.get(ConfigConstant.SYS_PAGINATE_PAGESIZE_NAME, "page_size"), PropKit.getInt(ConfigConstant.SYS_PAGINATE_PAGESIZE, 20));
    }

    protected AppBean getApp() {
        return getApp(getPara("app_id"));
    }

    protected AppBean getApp(String appId) {
        return AppRedis.getApp(appId);
    }

    protected UserBean getUser() {
        UserBean user = LoginRedis.getSessionUser(getPara("app_id"), getPara("token"), UserBean.class);
        if (!StrKit.notNull(user)) {
            throwError(APIResCode.SESSION_TIME_OUT);
        }
        return user;
    }

    protected String getUserId() {
        return getUser().getUser_id();
    }

    protected boolean isSuperAdmin() {
        return "1".equals(getUser().getIs_admin());
    }

    protected String getRequestIP() {
        return RequestKit.getRequestIp(getRequest());
    }

    protected String getNowDateTime() {
        return DateKit.getNowDateTime();
    }

    protected String getClientKey() {
        return getClientKey(getPara("server_id"));
    }

    protected String getClientKey(String serverId) {
        if (!ValidatorKit.validateUUID32(getPara("token"), false)) {
            throwError("用户登录状态错误");
        }
        if (!ValidatorKit.validateUUID32(serverId, false)) {
            throwError("docker服务标识错误");
        }
        //TODO 校验真实登录状态
        return DockerKit.key(getPara("token"), serverId);
    }

    protected SelfDockerClient getDockerClient() {
        return getDockerClient(getClientKey());
    }

    protected SelfDockerClient getDockerClient(String clientKey) {
        return DockerKit.getSeflClient(clientKey);
    }

    protected void refreshConnectTime() {
        refreshConnectTimeKey(getClientKey());
    }

    protected void refreshConnectTime(String serverId) {
        refreshConnectTimeKey(getClientKey(serverId));
    }

    protected void refreshConnectTimeKey(String clientKey) {
        DockerKit.refreshLCTime(clientKey);
    }

    protected void sendMsg(String connectKey, Object data) {
        WebsocketKit.sendMsg(connectKey, data);
    }

    protected void sendMsg(String connectKey, String cmd, Object data) {
        WebsocketKit.sendMsg(connectKey, cmd, data);
    }

    protected void sendMsg(Session session, Object data) {
        WebsocketKit.sendMsg(session, null, data);
    }

    protected void sendMsg(Session session, String cmd, Object data) {
        WebsocketKit.sendMsg(session, cmd, data);
    }

}


